package com.zmx.common.common.config.shardingsphere;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.util.Properties;

/**
 * @Description: 自定义配置文件 在application之前注入环境中
 * @ClassName: MyEnvironmentPostProcessor
 * @Author zhaomxr
 * @Date 2021-12-10 09:47
 */
@Slf4j
@ConditionalOnProperty(name = "application.datasource.type", havingValue = "shardingsphere", matchIfMissing = false)
public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {

    private final Properties properties = new Properties();

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        try {
            //自定义配置文件
            String[] profiles = {"shardingsphere.properties"};

            if (profiles != null && profiles.length > 0) {
                //循环添加
                for (String profile : profiles) {
                    //从classpath路径下面查找文件
                    Resource resource = new ClassPathResource(profile);
                    //加载成PropertySource对象，并添加到Environment环境中
                    environment.getPropertySources().addLast(loadProfiles(resource));
                }
            }
        } catch (Exception e) {
            log.error("加载自定义环境配置文件失败！", e);
        }
    }

    /**
     * 加载单个配置文件
     * @param resource
     * @return
     */
    private PropertySource<?> loadProfiles(Resource resource) {
        if (!resource.exists()) {
            throw new IllegalArgumentException("资源" + resource + "不存在");
        }
        try {
            //从输入流中加载一个Properties对象
            properties.load(resource.getInputStream());
            return new PropertiesPropertySource(resource.getFilename(), properties);
        } catch (IOException ex) {
            throw new IllegalStateException("加载配置文件失败" + resource, ex);
        }
    }
}
